import { Component } from "react";
import L from 'leaflet';
import "leaflet/dist/leaflet.css"
import { port, tileUrl, tiandituUrl } from "../../../assets/global";

class Map extends Component{
    constructor(props){
        super();
        this.map = new CreateMap("map");
    }

    componentDidMount() {
        this.map.init();
    }

    componentDidUpdate(){
        this.map.setCenter(this.props.curPort);
    }

    componentWillUnmount(){
        this.map.remove();
    }

    render(){
        return <div id="map" style={{height:"100%"}}></div>
    }
}

function CreateMap(id){
    this.id = id;
    this.map = null;
}

CreateMap.prototype.init = function (){
    let layers = {};
    for(let i = 2005; i < 2017; i++){
        layers[`${i}年`] = L.tileLayer(`${tileUrl}/${i}/{x}/{y}/{z}`, { "attribution": `${i}年12月` });
    }
    layers["2020年"] = L.tileLayer(tiandituUrl, { zoomOffset: 1, maxZoom: 15, "attribution": `2020年12月` });

    this.map = L.map("map", {
        layers: layers["2020年"],
        crs: L.CRS.EPSG4326,
        minZoom: 8,
        maxZoom: 15,
        zoom: 8,
        center: port["xuweiPort"].center,
        maxBounds: L.latLngBounds(L.latLng(34.14368517583559, 119.01757363060797), L.latLng(35.39581664260574, 120.45403603295172)),
        attributionControl: false,
        zoomControl: false
    });
    L.control.layers(layers).addTo(this.map);
    L.control.scale({ "imperial": false }).addTo(this.map);
    L.control.attribution({ "position": "topleft", "prefix": false }).addTo(this.map);
}

CreateMap.prototype.setCenter = function (curPort){
    if(!curPort){
        this.map.setView(port["xuweiPort"].center, 8)
    }
    else{
        this.map.setView(port[curPort].center, 11);
    }
}

CreateMap.prototype.remove = function(){
    this.map.remove();
}

export default Map;